class OauthController < ApplicationController
  include OauthModule

  VALIDATES = %w(weibo qq douban)

  before_action :set_provider, only: [:auth, :callback]

  def auth
    redirect_to @provider.authorize
  end

  def callback
    @provider.code = params[:code]
    @provider.access_client
    redirect_to @provider.return_url_after_auth
  end

  protected
  def set_provider
    provider = params[:provider]
    redirect_to root_url unless VALIDATES.include? provider
    klass = OauthProvider.const_get provider.camelize
    # 让 klass 实例可以访问 session
    accessor = instance_variable_get(:@_request)
    klass.send :define_method, 'session', -> { accessor.session }
    @provider = klass.new
  end
end